import os
import shutil
import logging
from django.core.management.base import BaseCommand
from django.conf import settings
from core.models import Advertisement

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = '将广告图片从ads/目录迁移到banners/目录，避免被广告拦截器屏蔽'

    def handle(self, *args, **options):
        # 确保banners目录存在
        banners_dir = os.path.join(settings.MEDIA_ROOT, 'banners')
        if not os.path.exists(banners_dir):
            os.makedirs(banners_dir)
            self.stdout.write(self.style.SUCCESS(f'创建banners目录: {banners_dir}'))
        
        # 创建默认广告图片
        default_banner_path = os.path.join(banners_dir, 'default-banner.jpg')
        default_ad_path = os.path.join(settings.MEDIA_ROOT, 'ads', 'default-ad.jpg')
        
        # 如果默认广告图片存在但默认banner图片不存在，则复制
        if os.path.exists(default_ad_path) and not os.path.exists(default_banner_path):
            shutil.copy(default_ad_path, default_banner_path)
            self.stdout.write(self.style.SUCCESS(f'创建默认banner图片: {default_banner_path}'))
        
        # 获取所有广告
        ads = Advertisement.objects.all()
        self.stdout.write(f'开始迁移 {ads.count()} 个广告图片...')
        
        for ad in ads:
            self.stdout.write(f'处理广告 ID: {ad.pk}, 标题: {ad.title}')
            
            if ad.image:
                original_path = ad.image.name
                
                # 只迁移ads目录下的图片
                if 'ads/' in original_path:
                    # 计算新的图片路径（将ads/替换为banners/）
                    new_path = original_path.replace('ads/', 'banners/')
                    
                    # 原始文件的完整路径
                    original_file_path = os.path.join(settings.MEDIA_ROOT, original_path)
                    
                    # 新文件的完整路径
                    new_file_path = os.path.join(settings.MEDIA_ROOT, new_path)
                    
                    try:
                        # 确保目标目录存在
                        os.makedirs(os.path.dirname(new_file_path), exist_ok=True)
                        
                        # 尝试复制文件
                        if os.path.exists(original_file_path):
                            shutil.copy(original_file_path, new_file_path)
                            self.stdout.write(self.style.SUCCESS(f'  图片已从 {original_file_path} 复制到 {new_file_path}'))
                            
                            # 更新数据库中的图片路径
                            ad.image.name = new_path
                            ad.save(update_fields=['image'])
                            self.stdout.write(self.style.SUCCESS(f'  成功更新图片路径: {original_path} -> {new_path}'))
                        else:
                            # 如果原文件不存在，则查找文件名
                            filename = os.path.basename(original_path)
                            possible_paths = [
                                os.path.join(settings.MEDIA_ROOT, filename),
                                os.path.join(settings.MEDIA_ROOT, 'ads', filename),
                            ]
                            
                            found = False
                            for possible_path in possible_paths:
                                if os.path.exists(possible_path):
                                    shutil.copy(possible_path, new_file_path)
                                    self.stdout.write(self.style.SUCCESS(f'  找到图片并复制: {possible_path} -> {new_file_path}'))
                                    
                                    # 更新数据库中的图片路径
                                    ad.image.name = new_path
                                    ad.save(update_fields=['image'])
                                    self.stdout.write(self.style.SUCCESS(f'  成功更新图片路径: {original_path} -> {new_path}'))
                                    found = True
                                    break
                            
                            # 如果仍找不到图片，使用默认图片
                            if not found and os.path.exists(default_banner_path):
                                shutil.copy(default_banner_path, new_file_path)
                                self.stdout.write(self.style.WARNING(f'  使用默认banner图片: {new_file_path}'))
                                
                                # 更新数据库中的图片路径
                                ad.image.name = new_path
                                ad.save(update_fields=['image'])
                                self.stdout.write(self.style.SUCCESS(f'  成功更新图片路径: {original_path} -> {new_path}'))
                    
                    except Exception as e:
                        self.stdout.write(self.style.ERROR(f'  处理广告图片时出错: {str(e)}'))
                        logger.error(f'处理广告图片时出错: {str(e)}', exc_info=True)
                else:
                    self.stdout.write(f'  图片路径已经不在ads目录下，无需迁移: {original_path}')
            else:
                self.stdout.write(self.style.WARNING(f'  广告没有图片: {ad.title}'))
        
        self.stdout.write(self.style.SUCCESS('图片迁移完成！'))
        self.stdout.write(self.style.WARNING('注意: 在生产环境中，您可能需要在web服务器配置中添加对/media/banners/路径的访问权限。')) 